﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Services.MSBuild.Tasks.Core;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using System.Collections;
using Microsoft.Build.Utilities;
using System.IO;
using Microsoft.Services.MSBuild.Tasks.Extensions;

namespace Microsoft.Services.MSBuild.Tasks
{
    public sealed class GetChangesetSpec
        : TaskBase
    {
        private static int GetChangesetId(string path)
        {
            WorkspaceInfo info = Workstation.Current.GetLocalWorkspaceInfo(path);

            TfsTeamProjectCollection collection = new TfsTeamProjectCollection(info.ServerUri);

            Workspace ws = info.GetWorkspace(collection);

            VersionControlServer vcs = collection.GetService<VersionControlServer>();

            IEnumerable changesets = null;

            VersionSpec spec = VersionSpec.ParseSingleSpec("W", ws.OwnerName);

            WorkspaceVersionSpec wvs = spec as WorkspaceVersionSpec;

            if (null != wvs && null == wvs.Name)
            {
                spec = new WorkspaceVersionSpec(ws.Name, ws.OwnerName);
            }

            changesets = vcs.QueryHistory(ws.GetServerItemForLocalItem(path), VersionSpec.Latest, 0, RecursionType.Full, null, new ChangesetVersionSpec(1), spec, 1, false, false).OfType<Changeset>().ToList();

            return changesets.Cast<Changeset>().First().ChangesetId;
        }

        [Required]
        public ITaskItem[] Items
        { get; set; }

        [Output]
        public ITaskItem[] ChangesetIds
        { get; set; }

        public override bool Execute()
        {
            ArrayList list = new ArrayList();

            foreach (ITaskItem item in this.Items)
            {
                ITaskItem destinationItem = new TaskItem(item);

                int changesetId = GetChangesetId(item.ItemSpec);

                destinationItem.SetMetadata("ChangesetId", changesetId.ToString());

                this.Log.LogMessage("ChangesetId: {0} ({1})", changesetId, item.ItemSpec);

                list.Add(destinationItem);
            }

            this.ChangesetIds = (ITaskItem[])list.ToArray(typeof(ITaskItem));

            return !base.Log.HasLoggedErrors;
        }
    }
}
